export default {
  data() {
    return {
    }
  },
  created() {
  },
  methods: {
    async downloadFile(url, filename, interval,needPre=true,needSuffix=true) {
      // console.log("filePath + url...", url)
      let response = await fetch(needPre?filePath+ url: url);
      let blob = await response.blob();
      let objectUrl = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.href = objectUrl;
      // console.log("filename", filename)
      let fn = url.substring(url.lastIndexOf('.'), url.lastIndexOf('?'))
      // console.log("fn", fn)
      a.download = filename + (needSuffix?fn:'');
      a.click();
      a.remove();
      this.loading = false;
      clearInterval(interval)
    },
    /**
    * @description: 下载
    * @return {*}
    */
    handleDownload(row) {
      let url = filePath + row.fileUrl;
      this.fileLinkToStreamDownload(url, row);
    },
    fileLinkToStreamDownload(url, row) {
      let fileName = row.fileName;
      let xhr = new XMLHttpRequest();
      xhr.open("get", url, true);
      xhr.setRequestHeader(
        "Content-Type",
        `application/pdf`,
        `application/msword`,
        `application/vnd.openxmlformats-officedocument.wordprocessingml.document`,
        `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,
        `image/png`,
        `image/jpeg`,
        `image/gif`,
        `text/plain`,
        `application/octet-stream`,
        `text/xml`
      );
      xhr.responseType = "blob";

      let that = this;
      xhr.onload = function () {
        if (this.status == 200) {
          //接受二进制文件流
          var blob = this.response;
          that.downloadExportFile(blob, fileName);
        }
      };
      xhr.send();
    },
    downloadExportFile(blob, tagFileName) {
      let downloadElement = document.createElement("a");
      let href = blob;
      if (typeof blob == "string") {
        downloadElement.target = "_blank";
      } else {
        href = window.URL.createObjectURL(blob); //创建下载的链接
      }
      downloadElement.href = href;
      //下载后文件名
      downloadElement.download = tagFileName+'.xlsx';
      downloadElement.click(); //点击下载
      if (document.body.downloadElement) {
        document.body.removeChild(downloadElement); //下载完成移除元素
      }
      if (typeof blob != "string") {
        window.URL.revokeObjectURL(href); //释放掉blob对象
      }
    },
  }
}
